import 'reflect-metadata'
import express from 'express'
import cors from 'cors'
import {join} from 'path'

import './setEnv.js'
import {connectRedisDataSource} from './redisDataSource.js'
import {connectMysqlDataSource} from './mysqlDataSource.js'
import {useRoutes} from './router.js'
import {getDirname} from '../utils/index.js'
import {logger} from '../utils/logger.js'

export async function run() {

	const {PORT} = process.env

	const dirname = getDirname();

	await connectRedisDataSource().then(redisClientPool => {
		console.log('REDIS连接成功')
		/*redisClientPool.set('test', 'test').then(res => {
			console.log('redis set test', res)
		})*/
	/*	redisClientPool.get('test').then(res => {
			console.log('redis get test', res)
		})*/
	})

	connectMysqlDataSource().then(connection => {
		console.log('MYSQL连接成功')
		console.log('项目根目录', dirname)

		const app = express()

		app.set("view engine", "ejs")
		app.set("views", join(dirname, 'pages'))

		app.use(cors());
		app.use(express.json())
		app.use(express.urlencoded({extended: false}))
		app.use('/static', express.static(join(dirname, 'public')))

		useRoutes(app)

		app.listen(PORT, () => {
			logger.log(`服务已在 ${PORT} 端口运行`)
		})
	})


	process.on('uncaughtException', (error) => {
		logger.error(`系统发生未捕获的异常: ${error}`);
	});

	process.on('unhandledRejection', (reason, promise) => {
		logger.error(`系统发生未处理的拒绝: ${promise} 原因是: ${reason}`);
	});
}
